﻿namespace Anley.DomainDrivenDesign.Contract.Validate;

/// <summary>
/// API验证元数据提供程序
/// </summary>
internal class ApiValidationMetadataProvider
    : IValidationMetadataProvider
{
    private ResourceManager _resourceManager;

    public ApiValidationMetadataProvider(
        ResourceManager resourceManager)
    {
        _resourceManager = resourceManager;
    }

    /// <summary>
    /// 创建验证元数据
    /// </summary>
    public void CreateValidationMetadata(
        ValidationMetadataProviderContext context)
    {
        // 非空值类型
        var typeInfo = context.Key.ModelType.GetTypeInfo();
        if (typeInfo.IsValueType && Nullable.GetUnderlyingType(typeInfo) == null)
            if (!context.ValidationMetadata.ValidatorMetadata.Any(m => m.GetType() == typeof(RequiredAttribute)))
                context.ValidationMetadata.ValidatorMetadata.Add(new RequiredAttribute());
        // 模型验证
        foreach (var attribute in context.ValidationMetadata.ValidatorMetadata)
        {
            var vAttr = attribute as ValidationAttribute;
            if (vAttr != null && vAttr.ErrorMessage == null && vAttr.ErrorMessageResourceName == null)
            {
                var name = vAttr.GetType().Name;
                vAttr.ErrorMessage = _resourceManager.GetString(name, CultureInfo.CurrentCulture);
            }
        }
    }
}